<template>
	<view>
		<wd-message-box />
		<wd-toast />
		<up-card :title="`审批任务【${item.name}】`" v-for="(item, index) in runningTasks" :key="index" :border="false">
			<template #body>
				<view class="" slot="body">
					<up-form labelPosition="left" :model="auditForms[index]" :rules="auditRule" :ref="'form' + index"
						labelWidth="150">
						<up-form-item label="流程名" borderBottom>
							{{ processInstance.name }}
						</up-form-item>
						<up-form-item label="流程发起人" borderBottom ref="item1">
							{{ processInstance?.startUser?.nickname }}
							<up-tag size="mini" type="info" :text="processInstance?.startUser?.deptName"></up-tag>
						</up-form-item>
						<view v-if="runningTasks[index].formId > 0">
							
								<form-create v-model="approveForms[index].value" v-model:api="approveFormFApis[index]"
								:option="approveForms[index].option" :rule="approveForms[index].rule" />
							
						
						</view>
						<up-form-item label="审批建议" borderBottom prop="reason">
							<up-input v-model="auditForms[index].reason" placeholder="请输入审批建议" border="none"></up-input>
						</up-form-item>
						<up-form-item label="抄送人" borderBottom v-model="auditForms[index].copyUserIds"
							placeholder="请选择抄送人">
							<wd-select-picker v-model="auditForms[index].copyUserIds" :columns="userOptions"
								placeholder="请选择抄送人" value-key="id" label-key="nickname" clearable
								filterable></wd-select-picker>
						</up-form-item>
					</up-form>

				</view>
			</template>
			<template #foot>
				<view>
					<view class="footer">
						<view style="display: flex;justify-content: space-evenly;margin-top: 10px;">
							<wd-button type="success" size="small" icon="check-bold"
								@click="handleAudit(item, true)">通过</wd-button>
							<wd-button type="error" size="small" icon="close-bold"
								@click="handleAudit(item, false)">不通过</wd-button>
							<wd-button type="primary" size="small" icon="edit-outline"
								@click="openTaskUpdateAssigneeForm(item.id)">转办</wd-button>

						</view>
						<view style="display: flex;justify-content: space-evenly;margin-top: 10px;">
							<wd-button type="primary" size="small" icon="picture"
								@click="handleDelegate(item)">委派</wd-button>
							<wd-button type="primary" size="small" icon="add" @click="handleSign(item)">加签</wd-button>
							<wd-button type="warning" size="small" icon="arrow-left1"
								@click="handleBack(item)">回退</wd-button>
						</view>
					</view>
				</view>
			</template>
		</up-card>
		<up-card :border="false">
			<template #head>
				<view class="flex justify-between">
					<view>审批信息【{{ processInstance.name }}】</view>
					<wd-button class="w-80px" type="success" size="small" @click="goBack">返回</wd-button>
				</view>
			</template>
			<template #body>
				<view class="" slot="body">
					<slot name="approval-info"></slot>
				</view>
			</template>

		</up-card>
		<!-- 审批记录 -->
		<ProcessInstanceTaskList :loading="tasksLoad" :process-instance="processInstance" :tasks="tasks"
			@refresh="getTaskList" />
		<view>
			&nbsp
		</view>
		<!-- 弹窗：转派审批人 -->
		<TaskTransferForm ref="taskTransferFormRef" @success="getDetail" />
		<!-- 弹窗：委派，将任务委派给别人处理，处理完成后，会重新回到原审批人手中-->
		<TaskDelegateForm ref="taskDelegateForm" @success="getDetail" />
		<!-- 弹窗：加签，当前任务审批人为A，向前加签选了一个C，则需要C先审批，然后再是A审批，向后加签B，A审批完，需要B再审批完，才算完成这个任务节点 -->
		<TaskSignCreateForm ref="taskSignCreateFormRef" @success="getDetail" />
		<!-- 弹窗：回退节点 -->
		<TaskReturnForm ref="taskReturnFormRef" @success="getDetail" />
	</view>
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { ref, unref, reactive, nextTick, getCurrentInstance, onMounted } from 'vue'
import { isEmpty } from '@/utils/is'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { setConfAndFields2 } from '@/utils/formCreate'
import * as DefinitionApi from '@/api/bpm/definition'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import * as TaskApi from '@/api/bpm/task'
import * as UserApi from '@/api/system/user'
import { useApprovedTasksStore } from '@/store/modules/approvedTasksStore';
import { useUserStore } from '@/store/modules/user'
import { formatDate, formatPast2 } from '@/utils/formatTime'
import { useMessage, useToast } from 'wot-design-uni'
import ProcessInstanceTaskList from './ProcessInstanceTaskList.vue'
import TaskTransferForm from './dialog/TaskTransferForm.vue'
import TaskDelegateForm from './dialog/TaskDelegateForm.vue'
import TaskSignCreateForm from './dialog/TaskSignCreateForm.vue'
import TaskReturnForm from './dialog/TaskReturnForm.vue'
import FormCreate from '@/components/formcreate/index.vue'



const props = defineProps<{
	processInstanceId?: any; // 允许对象，但不限制具体字段
}>();
const { proxy } = getCurrentInstance() as any
const approvedTasksStore = useApprovedTasksStore();
const toast = useToast()
const userId = useUserStore().getUser.id // 当前登录的编号
const userOptions = ref<any[]>([]) // 用户列表
const processInstanceId = ref(null)// 流程实例的编号
const id = ref(null)
const processInstanceLoading = ref(false) // 流程实例的加载中
const processInstance = ref<any>({}) // 流程实例
const tasksLoad = ref(true) // 任务的加载中
const tasks = ref<any[]>([]) // 任务列表

// ========== 审批信息 ==========
const runningTasks = ref<any[]>([]) // 运行中的任务
const auditForms = ref<any[]>([]) // 审批任务的表单
const auditRule = reactive({
	reason: [{ required: true, message: '审批建议不能为空', trigger: 'blur' }]
})
const approveForms = ref<any[]>([]) // 审批通过时，额外的补充信息
const approveFormFApis = ref<any>([]) // approveForms 的 fAPi
// ========== 审批信息 ==========
// const formData = ref<LawContractReviewVO>({} as any)

const formFields = ref<any[]>([]);
// ========== 申请信息 ==========
const fApi = ref<any>() //
const detailForm = ref({
	rule: [],
	option: {},
	value: {}
}) // 流程实例的表单详情

onMounted(async () => {
	processInstanceId.value = props.processInstanceId;
	if (processInstanceId.value) {
		getDetail()
	}
	try {
		userOptions.value = await UserApi.getSimpleUserList();
	} catch (error) {
		console.error("获取用户列表失败:", error);
		userOptions.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
})
const goBack = () => {
	uni.navigateBack()
}
const getDict = (type: any, value: any) => {
	const dicts = getIntDictOptions(type)
	const dict = dicts.find(item => item.value === value)
	return dict ? dict.label : '待审批'
}
/** 子任务 */
const taskSignListRef = ref()
const openChildrenTask = (item: any) => {
	console.log('dianjil');
	taskSignListRef.value.open(item)
}
//审批通过之后让父组件刷新审批表单的数据
const emit = defineEmits(['success'])
/** 审批操作*/
/** 处理审批通过和不通过的操作 */
const handleAudit = async (task: any, pass: any) => {
	// 1.1 获得对应表单
	const index = runningTasks.value.indexOf(task)
	const auditFormRef = proxy.$refs['form' + index][0]
	// 1.2 校验表单
	const elForm = unref(auditFormRef)
	if (!elForm) return
	const valid = await elForm.validate()
	if (!valid) return

	// 2.1 提交审批
	const resonAndAuditor = {
		reason: auditForms.value[index].reason,
		auditor: auditForms.value[index].auditUserIds,
		auditDepIds: auditForms.value[index].auditDepIds
	}
	const data: any = {
		id: task.id,
		// reason: JSON.stringify(resonAndAuditor),
		reason: auditForms.value[index].reason,
		copyUserIds: auditForms.value[index].copyUserIds
	}
	const approvedTasks = {
		id: task.id,
		taskName: task.name,
		assigneeUser: task.assigneeUser,
		reason: auditForms.value[index].reason, // 假设任务中有 reason 属性存储审批原因

		copyUserIds: auditForms.value[index].copyUserIds
	}
	if (pass) {
		// 审批通过，并且有额外的 approveForm 表单，需要校验 + 拼接到 data 表单里提交
		const formCreateApi = approveFormFApis.value[index]
		console.log('approveFormFApis.value[index]', approveFormFApis.value[index]);
		console.log('formCreateApi', formCreateApi);

		if (formCreateApi) {
			console.log('approveForms.value[index].value', approveForms.value[index].value);
			console.log('formCreateApi', formCreateApi);

			// await formCreateApi.validate()
			const valid = await formCreateApi.validate()
			if (!valid) return
			data.variables = approveForms.value[index].value
		}
		console.log('data表单提交数据', data);

		await TaskApi.approveTask(data)
		toast.success('审批通过成功')
	} else {
		await TaskApi.rejectTask(data)
		toast.success('审批不通过成功')
	}
	// ✅ 通知父组件刷新数据
	emit('success') 
	// 2.2 加载最新数据
	getDetail()
}
/** 转派审批人 */
const taskTransferFormRef = ref()
const openTaskUpdateAssigneeForm = (id: string) => {
	taskTransferFormRef.value.open(id)
}

/** 处理审批委派的操作 */
const taskDelegateForm = ref()
const handleDelegate = async (task: any) => {
	taskDelegateForm.value.open(task.id)
}

/** 处理审批退回的操作 */
const taskReturnFormRef = ref()
const handleBack = async (task: any) => {
	taskReturnFormRef.value.open(task.id)
}

/** 处理审批加签的操作 */
const taskSignCreateFormRef = ref()
const handleSign = async (task: any) => {
	taskSignCreateFormRef.value.open(task.id)
}
/** 获得流程实例和任务对应的颜色 */
const getNodeClassOrType = (item: any) => {
	const statusMap: Record<number, { type: string; color: string }> = {
		0: { type: 'primary', color: '#409eff' },
		1: { type: 'primary', color: '#409eff' },
		2: { type: 'success', color: '#67c23a' },
		3: { type: 'error', color: '#f56c6c' },
		4: { type: 'info', color: '#909399' },
		5: { type: 'warning', color: '#e6a23c' },
		6: { type: 'primary', color: '#409eff' },
		7: { type: 'primary', color: '#409eff' }
	};

	return statusMap[item.status] || { type: 'primary', color: '#67c23a' };
};
const getDetail = () => {
	// 1. 获得流程实例相关
	getProcessInstance()
	// 2. 获得流程任务列表（审批记录）
	getTaskList()
	//3.获取页面详情
	// getLawContractReviewById()

}
/** 加载流程实例 */
const BusinessFormComponent = ref<any>(null) // 异步组件
const getProcessInstance = async () => {
	try {
		processInstanceLoading.value = true
		const data = await ProcessInstanceApi.getProcessInstance(processInstanceId.value as any)
		if (!data) {
			toast.error('查询不到流程信息！')
			return
		}
		processInstance.value = data

		// 设置表单信息
		const processDefinition = data.processDefinition
		if (processDefinition.formType === 10) {
			setConfAndFields2(
				detailForm,
				processDefinition.formConf,
				processDefinition.formFields,
				data.formVariables
			)
			nextTick().then(() => {
				fApi.value?.btn.show(false)
				fApi.value?.resetBtn.show(false)
				fApi.value?.disabled(true)
			})
		} else {

			// 注意：data.processDefinition.formCustomViewPath 是组件的全路径，例如说：/crm/contract/detail/index.vue
			// BusinessFormComponent.value = registerComponent(data.processDefinition.formCustomViewPath as any)
		}

		// 加载流程图
		// bpmnXml.value = (
		// 	await DefinitionApi.getProcessDefinition(processDefinition.id as any)
		// )?.bpmnXml
	} finally {
		processInstanceLoading.value = false
	}
}

/** 加载任务列表 */
const getTaskList = async () => {
	runningTasks.value = []
	auditForms.value = []
	approveForms.value = []
	approveFormFApis.value = []
	// approvedTasks.value = [] // 用于存储已通过的任务信息
	try {
		// 获得未取消的任务
		tasksLoad.value = true
		const data = await TaskApi.getTaskListByProcessInstanceId(processInstanceId.value as any)
		tasks.value = []
		// 1.1 移除已取消的审批
		data.forEach((task: any) => {
			if (task.status !== 4) {
				tasks.value.push(task)
				if (task.status === 2) { // status 为 2 即为通过
					// approvedTasks.value.push({
					//   taskName: task.name,
					//   assigneeUser: task.assigneeUser,
					//   reason: task.reason, // 假设任务中有 reason 属性存储审批原因
					// })
				}
			}
		})


		// 1.2 排序，将未完成的排在前面，已完成的排在后面；
		tasks.value.sort((a, b) => {
			// 有已完成的情况，按照完成时间倒序
			if (a.endTime && b.endTime) {
				return b.endTime - a.endTime
			} else if (a.endTime) {
				return 1
			} else if (b.endTime) {
				return -1
				// 都是未完成，按照创建时间倒序
			} else {
				return b.createTime - a.createTime
			}
		})
		// 获得需要自己审批的任务
		loadRunningTask(tasks.value)
	} finally {
		tasksLoad.value = false
	}
}
/**
 * 设置 runningTasks 中的任务
 */
const loadRunningTask = (tasks: any) => {

	tasks.forEach((task: any) => {
		if (!isEmpty(task.children)) {
			loadRunningTask(task.children)
		}
		// 2.1 只有待处理才需要
		if (task.status !== 1 && task.status !== 6) {
			return
		}
		// 2.2 自己不是处理人
		if (!task.assigneeUser || task.assigneeUser.id !== userId) {
			return
		}
		// 2.3 添加到处理任务
		runningTasks.value.push({ ...task })
		auditForms.value.push({
			reason: '',
			copyUserIds: []
		})
		console.log('task', task);
		console.log('runningTasks.value', runningTasks.value);
		console.log('auditForms.value', auditForms.value);

		// 2.4 处理 approve 表单
		if (task.formId && task.formConf) {
			const approveForm = {}
			setConfAndFields2(approveForm, task.formConf, task.formFields, task.formVariables)
			approveForms.value.push(approveForm)
			console.log('approveForms.value', approveForms.value);

		} else {
			approveForms.value.push({}) // 占位，避免为空
		}
	})
}
</script>

<style>
/* 样式 */
.u-card-wrap {
	/* background-color: $up-bg-color; */
	/* padding:10px 1px; */
}

.uv-node {
	height: 34rpx;
	width: 34rpx;
	border-radius: 50%;
	background-color: #ddd;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	flex-shrink: 0;
	z-index: -1;
}

.audit-node {
	margin: 5px 0;
}
</style>